//
//  PELocalBatteryLoadChartView.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/29.
//

#import "RHLocalBatteryCellChartView.h"
#import "DevChartModel.h"
#import "QMUILabel+LHAdd.h"
#import "DeviceChartFieldModel.h"
#import "DeviceChartItemView.h"
#import "NSString+LenWid.h"
#import "RHMaskView.h"
#import "RHLeftAxisFormatter.h"
#import "RHRightAxisFormatter.h"

@interface RHLocalBatteryCellChartView()<ChartAxisValueFormatter>
@property (nonatomic ,copy) NSArray *colorList;

@property (nonatomic ,strong) QMUIButton *l_btn;

@property (nonatomic ,strong) QMUIButton *r_btn;

@property (nonatomic ,strong) QMUIButton *timeBtn;
/// 图表
@property (nonatomic, strong) LineChartView *lineChartView;
//气泡
@property (nonatomic, strong) RHMaskView *maskView;
//左边Y轴单位
@property (nonatomic, strong) QMUILabel *leftUnitLab;
//右边Y轴单位
@property (nonatomic, strong) QMUILabel *rightUnitLab;

@property (nonatomic ,assign) NSInteger type;

@property (nonatomic, strong) UIView *scrollBgView;

@property (nonatomic, strong) UIScrollView *scroll;

@property (nonatomic, strong) UIView *contentView;

/// 本地json数据文件名
@property (nonatomic, strong) NSString *jsonName;

@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, strong) NSMutableArray *itemsArray;

@property (nonatomic, strong) NSMutableArray *pointViewArr;

@property (nonatomic, strong) NSMutableArray *unitArr;
@end
@implementation RHLocalBatteryCellChartView

- (instancetype)initWithFrame:(CGRect)frame type:(NSInteger)type{
    self = [super initWithFrame:frame];
    if (self) {
        self.colorList = @[@"#FFCE00",@"#678EF2",@"#10E2FF",@"#58C373",@"#FB8480"];
        self.type = type;
        [self setupUI];
  
    }
    return self;
}

- (NSMutableArray *)itemsArray{
    if (!_itemsArray) {
        _itemsArray = [NSMutableArray array];
    }
    return _itemsArray;
}

- (void)setupUI{
    [self setBackgroundColor:UIColor.whiteColor];
    UIView *itemBgView = [[UIView alloc] init];
    [itemBgView setBackgroundColor:UIColor.whiteColor];
    [self addSubview:itemBgView];
    
    kWeakSelf;
   
    QMUIButton *dateBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [dateBtn setBackgroundColor:UIColor.whiteColor];
    [dateBtn setTitle:@"2023-08-09" forState:UIControlStateNormal];

    [dateBtn setTitleColor:FontColor(@"#000000") forState:UIControlStateNormal];
    [dateBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [self addSubview:dateBtn];
    self.timeBtn = dateBtn;
    
    _l_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_l_btn setImage:[UIImage imageNamed:@"day_left"] forState:UIControlStateNormal];
    [self addSubview:_l_btn];
    
    _r_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_r_btn setImage:[UIImage imageNamed:@"day_right"] forState:UIControlStateNormal];
    [self addSubview:_r_btn];

    [self addSubview:self.lineChartView];
    
    dateBtn.hidden = YES;
    _l_btn.hidden = YES;
    _r_btn.hidden = YES;
    
    
    //添加单位
    QMUILabel *leftUnitLab = [[QMUILabel alloc]init];
    leftUnitLab.textColor = UIColor.lightGrayColor;
    leftUnitLab.font = [UIFont systemFontOfSize:13];
    [self addSubview:leftUnitLab];
    self.leftUnitLab = leftUnitLab;
    
    QMUILabel *rightUnitLab = [[QMUILabel alloc]init];
    rightUnitLab.textColor = UIColor.lightGrayColor;
    rightUnitLab.font = [UIFont systemFontOfSize:13];
    [self addSubview:rightUnitLab];
    self.rightUnitLab = rightUnitLab;
    
    [leftUnitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.lineChartView).offset(5);
        make.bottom.equalTo(weakSelf.lineChartView.mas_top).offset(0);
    }];
    
    [rightUnitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.lineChartView).offset(-5);
        make.bottom.equalTo(weakSelf.lineChartView.mas_top).offset(0);
    }];
    
    _scrollBgView = [[UIView alloc] init];
    [_scrollBgView setBackgroundColor:UIColor.orangeColor];
    [self addSubview:_scrollBgView];
    
    _scroll = [[UIScrollView alloc] init];
    [_scroll setShowsHorizontalScrollIndicator:NO];
    _scroll.backgroundColor = [UIColor whiteColor];
    [_scrollBgView addSubview:_scroll];
    
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = [UIColor whiteColor];
    [_scroll addSubview:_contentView];
    
    __block DeviceChartItemView *lastItem;
    __block CGFloat width = 5;
    [self.colorList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DeviceChartItemView *itemView = [[DeviceChartItemView alloc] init];
        [itemView.markLab.layer setBorderColor:FontColor(obj).CGColor];
//        [itemView shadow:UIColor.blackColor opacity:0.1 radius:5 offset:CGSizeMake(0, 1)];
        [_contentView addSubview:itemView];
        [self.itemsArray addObject:itemView];

        if (!lastItem) {
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(width);
                make.top.mas_offset(5);
                make.centerY.mas_offset(0);
                make.height.mas_equalTo(20);
                make.width.mas_equalTo(0);
            }];
            width = width;
        }else{
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastItem.mas_right).offset(5);
                make.top.mas_offset(5);
                make.centerY.mas_offset(0);
                make.height.mas_equalTo(20);
                make.width.mas_equalTo(0);
            }];
            width = width+5;
        }
        lastItem = itemView;
    }];
    
    [lastItem mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(0);
    }];
    
    [itemBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(5);
        make.left.mas_offset(10);
        make.width.greaterThanOrEqualTo(@0.f);
    }];
    
   
    
    [dateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(90, 30));
        make.centerX.mas_offset(0);
        make.top.mas_offset(15);
    }];
    
    [_l_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 30));
        make.centerY.equalTo(dateBtn);
        make.right.equalTo(dateBtn.mas_left);
    }];

    [_r_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 30));
        make.centerY.equalTo(dateBtn);
        make.left.equalTo(dateBtn.mas_right);
    }];
    
    [self.lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(5);
        make.right.mas_offset(-5);
        make.top.equalTo(dateBtn.mas_bottom).offset(5);
       
       
    }];
    
    [self.scrollBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.equalTo(self.lineChartView.mas_bottom).offset(0);
        make.bottom.mas_offset(-10);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(MIN(self.frame.size.width,width));
    }];
    
    [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.greaterThanOrEqualTo(@0.f);//此处保证容器View高度的动态变化 大于等于0.f的高度
    }];
 
    
   

}


- (void)fullAction{
    if (self.fullChartBlock) {
        self.fullChartBlock();
    }
}



- (void)setChartModel:(DevChartModel *)chartModel{
   
    _chartModel = chartModel;
    self.selectIndex = _chartModel.timeType;

    [self setChartData];
    
    NSString *timeStr;
    if (_chartModel.timeType == TimeType_Day) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        NSString *dateTime = [formatter stringFromDate:date];
        timeStr = dateTime;
        [_r_btn setEnabled:[date isToday]?NO:YES];
    }else if (_chartModel.timeType == TimeType_Month) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        timeStr = [NSString stringWithFormat:@"%02ld-%02ld",[date year],[date month]];
        [_r_btn setEnabled:[[NSDate date] monthsLaterThan:date]?YES:NO];
    }else if (_chartModel.timeType == TimeType_Year){
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        timeStr = [NSString stringWithFormat:@"%ld",[date year]];
        [_r_btn setEnabled:[[NSDate date] yearsLaterThan:date]?YES:NO];
    }else{
        timeStr = @"";
    }

    [self.timeBtn setTitle:ValidStr(timeStr)?timeStr:@"" forState:UIControlStateNormal];
    
    __block CGFloat total_width = 0;
    
    
    kWeakSelf;
    [self.itemsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat item_width = 0;
        DeviceChartFieldModel *model;
        DeviceChartItemView *itemView = obj;
        if (idx<self.chartModel.selectArray.count) {
            model = self.chartModel.selectArray[idx];
            model.colorStr = self.colorList[idx];
            [itemView setModel:model];
            NSAttributedString *attr = [[NSAttributedString alloc] initWithString:model.keyName];
            CGSize size = [itemView.conentLab getLableSizeWithAttStr:attr maxHeight:15];
            item_width = size.width+25;
            [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(item_width);
            }];
            [itemView setHidden:NO];
            total_width = total_width+item_width+5;
        }else{
            [itemView setHidden:NO];
            [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(0);
            }];
        }
        
        [self.scrollBgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(MIN(self.frame.size.width,total_width+5));
        }];
    
        itemView.selectBlock = ^BOOL(DeviceChartFieldModel * _Nonnull model) {
            model.isShowLine = !model.isShowLine;
            [weakSelf.chartModel updateyAxisArray];
            [weakSelf setChartData];
            return YES;
        };
    }];
    
   
}

#pragma mark ---- 设置曲线数据 ------
-(void)setChartData
{
    [self.lineChartView clear];
    self.leftUnitLab.hidden = YES;
    self.rightUnitLab.hidden = YES;
//    NSLog(@"----->111 chart model count:%ld",self.chartModel.selectArray.count);
    //X轴要显示的数据
    //没有数据的时候也展示

    
    [self.lineChartView.xAxis setLabelCount:10 force:YES];//设置x轴显示的个数
  
//    self.lineChartView.xAxis.granularity = self.chartModel.xTitlesArray.count/labelCount;
    
//    NSLog(@"----->lebelCount:%d\n ----->granularity:%f\n ----->xTitlesArrayCount:%d\n----->chartViewLabelCount:%f",labelCount,self.lineChartView.xAxis.granularity,self.chartModel.xTitlesArray.count,self.lineChartView.xAxis.labelCount);
    NSLog(@"------>label_width111=%f",self.lineChartView.xAxis.labelWidth);
//    self.lineChartView.xAxis.forceLabelsEnabled = YES; //数据点强制显示个数
//    if(self.width>self.height){
//        self.lineChartView.xAxis.axisMaxLabels = 12;
//    }
//    //根x轴据数据多少,再显示几个数,确保数据小的时候显示全部横轴数据
//    if(self.chartModel.xTitlesArray.count>5){
//        self.lineChartView.xAxis.granularity = 1.5;//x轴间隔多少个数据显示
//    }else{
//        self.lineChartView.xAxis.granularity = 1;
//    }
//    self.lineChartView.maxVisibleCount = labelCount;
    NSString *time = @"11:23";
    CGFloat width = [time getStringWidthFont:self.lineChartView.xAxis.labelFont limitHeight:25];
    NSLog(@"----->text height:%f",width);
    [self.unitArr removeAllObjects];
    kWeakSelf;
    //将 LineChartDataSet 对象放入数组中
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    __block CGFloat left_y_max = 0;
    __block CGFloat right_y_max = 0;
    __block CGFloat left_y_min = 0;
    __block CGFloat right_y_min = 0;
    [self.chartModel.selectArray enumerateObjectsUsingBlock:^(DeviceChartFieldModel  *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {

//        NSLog(@"----->index:%ld uint:%@",idx,model.unitName);
        if(model.isShowLine){
            
            LineChartDataSet *set = [self createDataSetWithModel:model linecolor:self.colorList[idx]];
            //单位
            if(![weakSelf.unitArr containsObject:model.unitName]){
                [weakSelf.unitArr addObject:ValidNullDataToString(model.unitName, @"--")];
            }
            //数据对应 左边Y轴 还是 右边Y轴
            if(weakSelf.unitArr.count<2){
                set.axisDependency = AxisDependencyLeft;
                //因为只有两条,直接写最大最小值
                left_y_max = model.y_max;
                left_y_min = model.y_min;
                self.leftUnitLab.text = model.unitName;
                self.leftUnitLab.hidden = NO;
                NSLog(@"---->111111");
            }else{
                //两个单位
                if([model.unitName isEqualToString:weakSelf.unitArr[0]]){
                    set.axisDependency = AxisDependencyLeft;
                    left_y_max = model.y_max;
                    left_y_min = model.y_min;
                    NSLog(@"---->222222");
                }else{
                    self.lineChartView.rightAxis.enabled = YES;
                    set.axisDependency = AxisDependencyRight;
                    right_y_max = model.y_max;
                    right_y_min = model.y_min;
                    self.rightUnitLab.text = model.unitName;
                    self.rightUnitLab.hidden = NO;
                    NSLog(@"---->333333");
                }
                
                
            }
            
            [dataSets addObject:set];
        }
        
    }];
    NSLog(@"------>左轴最大值:%f",left_y_max);
    NSLog(@"------>右轴最大值:%f",right_y_max);
    NSLog(@"------>左轴最小值:%f",left_y_min);
    NSLog(@"------>右轴最小值:%f",right_y_min);
    self.lineChartView.leftAxis.axisMaximum = left_y_max;
    self.lineChartView.rightAxis.axisMaximum = right_y_max;
    self.lineChartView.leftAxis.axisMinimum = left_y_min;
    self.lineChartView.rightAxis.axisMinimum = right_y_min;
    //没有数据的时候也展示
    if(left_y_max == 0)
    {
        left_y_max = 100;
    }
    if(right_y_max == 0){
        right_y_max = 100;
    }
    //创建 LineChartData 对象, 此对象就是lineChartView需要最终数据对象
    LineChartData *lineData = [[LineChartData alloc] initWithDataSets:dataSets];
    self.lineChartView.data = lineData;
    //这里可以调用一个加载动画即1s出来一个绘制点
//    [self.lineChartView animateWithXAxisDuration:0.2f];
    //通知data去更新
    [self.lineChartView.data notifyDataChanged];
    //通知图表去更新
    [self.lineChartView notifyDataSetChanged];
//    NSLog(@"------>label_width222=%f",self.lineChartView.xAxis.labelWidth);
    
    
//    NSLog(@"----->333%@",self.lineChartView.xAxis.yy_modelDescription);
}

#pragma mark ----- 创建曲线
-(LineChartDataSet*)createDataSetWithModel:(DeviceChartFieldModel*)model linecolor:(NSString*)colorStr;
{
    
    NSMutableArray *entryArr = [[NSMutableArray alloc]init];
    
    [self.chartModel.xTitlesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:idx y:[model.dataArray[idx] floatValue]];
        [entryArr addObject:entry];
        NSLog(@"------->添加entry:%f",[model.dataArray[idx] floatValue]);
    }];
    
    LineChartDataSet *set = [[LineChartDataSet alloc] initWithEntries:entryArr label:model.keyName];
    [set setColor:kCOLOR_HEX(colorStr)];//折线颜色
    //set1.lineDashLengths = @[@4.0,@2.0];//设置虚线各段长度
    set.mode = LineChartModeHorizontalBezier;//曲线平滑显示   贝塞尔曲线
    
    set.drawIconsEnabled = YES;//是否绘制图标
    set.formLineWidth = 1.1;//图例的线宽
    set.formSize = 8.0;//图例的字体大小
    set.lineWidth = 2.0;//折线的宽度
    

    set.drawCirclesEnabled = NO;//是否绘制拐点
    set.drawCircleHoleEnabled = YES;//是否画空心圆
    set.circleColors = @[kCOLOR_HEX(colorStr)];//外圆颜色
    set.circleHoleColor = UIColor.whiteColor; //内圆颜色
    set.circleRadius = 2; //外圆半径
    set.circleHoleRadius = 1; //内圆半径
    
    set.drawValuesEnabled = NO;//是否在拐点处显示数据
    set.valueColors = @[kCOLOR_HEX(colorStr)];//拐点上的文字颜色
    set.valueFont = [UIFont systemFontOfSize:8];//拐点上的文字大小
    
    //折线拐点样式
    //第二种填充样式:渐变填充
    set.drawFilledEnabled = YES;//是否填充颜色
    NSArray *gradientColors = @[(id)[UIColor colorWithHexString:colorStr alpha:0.5].CGColor,
                                (id)[UIColor colorWithHexString:colorStr alpha:0.1].CGColor];
    CGGradientRef gradientRef = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil);
    set.fillAlpha = 1.0f;//透明度
    set.fill = [[ChartLinearGradientFill alloc]initWithGradient:gradientRef angle:-90.0f];//赋值填充颜色对象
    CGGradientRelease(gradientRef);//释放gradientRef
    
    //点击选中拐点的交互样式
    set.highlightEnabled = YES;//选中拐点,是否开启高亮效果(显示十字线)
//    set.drawVerticalHighlightIndicatorEnabled = NO; //不显示纵向十字线
    set.drawHorizontalHighlightIndicatorEnabled = NO; //不显示横向十字线
    set.highlightColor = kRGB(23,23,23);//点击选中拐点的十字线的颜色
    set.highlightLineWidth = 1.1/[UIScreen mainScreen].scale;//十字线宽度
    set.highlightLineDashLengths = @[@5, @5];//十字线的虚线样式
    
    return set;
}

- (LineChartView *)lineChartView{
    if (!_lineChartView) {
        _lineChartView = [[LineChartView alloc] initWithFrame:CGRectMake(0, 0,self.frame.size.width-10,self.frame.size.height-155)];
        _lineChartView.delegate = self;
        
        _lineChartView.chartDescription.enabled = NO;  //是否显示描述label
//        _lineChartView.extraRightOffset = 40;//右边缩进
        _lineChartView.extraBottomOffset = 10;//图表底部缩进,也就是与图例的距离
        _lineChartView.backgroundColor = kRGB(255, 255, 255);

        _lineChartView.noDataText = @"no data...";//没有数据时显示的文字
       
        _lineChartView.legend.enabled = NO;//是否显示说明图标
        _lineChartView.legend.form = ChartLegendFormSquare;//说明图例的样式  --指导价走势
        _lineChartView.legend.formSize = 3;//图例大小（头部）
        _lineChartView.legend.formToTextSpace = 5;//图例与文字的距离
        _lineChartView.legend.yOffset = 10;//图例与底部的距离
        _lineChartView.legend.xEntrySpace = 20;//图例与图例之间的距离
        _lineChartView.legend.neededHeight = 50;
        _lineChartView.legend.stackSpace = 10;
        _lineChartView.dragEnabled = YES; //拖动手势
        _lineChartView.dragDecelerationEnabled = YES;//拖拽后是否有惯性效果
        _lineChartView.dragDecelerationFrictionCoef = 0.9;//拖拽后惯性效果的摩擦系数(0~1)，数值越小，惯性越不明显
        _lineChartView.pinchZoomEnabled = YES; //捏合手势
        _lineChartView.rightAxis.enabled = YES;  //隐藏右Y轴
        _lineChartView.doubleTapToZoomEnabled = NO;  //禁止双击缩放
        _lineChartView.drawGridBackgroundEnabled = NO; //绘制图形区域背景
        _lineChartView.drawBordersEnabled = NO; //绘制图形区域边框
        _lineChartView.scaleYEnabled = NO;//Y轴不允许缩放
        _lineChartView.highlightPerTapEnabled = YES;//高亮点击
        _lineChartView.highlightPerDragEnabled = NO;//高亮拖拽
//        [_lineChartView setVisibleXRangeMaximum:8];// 最大显示区域
//        [_lineChartView setVisibleXRangeMinimum:2];// 最小显示区域
//
        
        _lineChartView.drawMarkers = YES;
        //气泡标签
        ChartMarkerView *marker = [[ChartMarkerView alloc]
                                 init];
        marker.offset = CGPointZero;
        marker.chartView = _lineChartView;
//        marker.minimumSize = CGSizeMake(60.f, 20.f);
//        marker.image = [UIImage imageNamed:@""];
        
        RHMaskView *maskView = [[RHMaskView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
        [marker addSubview:maskView];
        self.maskView = maskView;
        _lineChartView.marker = marker;
        
       
        //只滑动不缩放
    //    ChartViewPortHandler *scalX = self.LineChartView.viewPortHandler;
    //    [scalX setMinimumScaleX:1.01];
        
        
        //设置 左<--Y轴
        ChartYAxis *leftAxis =_lineChartView.leftAxis;
        leftAxis.labelPosition = YAxisLabelPositionOutsideChart;//label位置
        leftAxis.axisLineWidth = 1;
        leftAxis.axisMaxLabels = 6;     //y轴展示多少个
        [leftAxis setLabelCount:6 force:YES];
        leftAxis.labelFont = [UIFont systemFontOfSize:12];
        leftAxis.labelTextColor = UIColor.lightGrayColor; //文本颜色
        leftAxis.axisLineColor = kRGB(217, 217, 217);    //左Y轴线条颜色
        leftAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线
        leftAxis.gridColor = [UIColor colorWithRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1];//网格线颜色
        leftAxis.gridAntialiasEnabled = YES;//开启抗锯齿
        leftAxis.zeroLineColor = [UIColor redColor];    //左Y轴底线条颜色
        leftAxis.drawZeroLineEnabled = NO;//绘制0线
//        leftAxis.valueFormatter = [[RHLeftAxisFormatter alloc]initWithUnitArr:self.unitArr];
        leftAxis.valueFormatter = self;
        leftAxis.axisMinimum = 0;//Y轴最小值
//        leftAxis.axisMaximum = 100;   //Y轴最大值
        leftAxis.drawAxisLineEnabled = NO;
        
        //设置 右-->Y轴
        ChartYAxis *rightAxis =_lineChartView.rightAxis;
        rightAxis.labelPosition = YAxisLabelPositionOutsideChart;//label位置
        rightAxis.axisLineWidth = 1;
        rightAxis.axisMaxLabels = 6;     //y轴展示多少个
        [rightAxis setLabelCount:6 force:YES];
        rightAxis.labelFont = [UIFont systemFontOfSize:12];
        rightAxis.labelTextColor = UIColor.lightGrayColor; //文本颜色
        rightAxis.axisLineColor = kRGB(217, 217, 217);    //左Y轴线条颜色
        rightAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线
        rightAxis.gridColor = [UIColor colorWithRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1];//网格线颜色
        rightAxis.gridAntialiasEnabled = YES;//开启抗锯齿
        rightAxis.zeroLineColor = [UIColor redColor];    //左Y轴底线条颜色
        rightAxis.drawZeroLineEnabled = NO;//绘制0线
//        rightAxis.valueFormatter = [[RHRightAxisFormatter alloc]initWithUnitArr:self.unitArr];
        rightAxis.valueFormatter = self;
        rightAxis.axisMinimum = 0;//Y轴最小值
//        rightAxis.axisMaximum = 100;   //Y轴最大值
        rightAxis.drawAxisLineEnabled = NO;
        
        // 设置X轴
        ChartXAxis *xAxis =_lineChartView.xAxis;
        xAxis.axisLineWidth = 1.0/[UIScreen mainScreen].scale;//设置X轴线宽
        xAxis.axisLineColor = UIColor.lightGrayColor;
        xAxis.labelPosition =XAxisLabelPositionBottom; //x轴文字的位置
        xAxis.labelFont = [UIFont systemFontOfSize:12];//文字字体
        xAxis.labelTextColor = UIColor.lightGrayColor;//文字颜色
        xAxis.axisMaxLabels = 15;//x轴最多显示个数;
        xAxis.axisMinLabels = 1;//x轴最少显示个数;
        xAxis.granularity = 1;//x轴标题中间最小的间隔。
        xAxis.drawAxisLineEnabled = YES;//是否画x轴线
//        xAxis.granularityEnabled = YES;//设备重复不显示
//        xAxis.forceLabelsEnabled = NO; //数据点强制显示个数
//        xAxis.avoidFirstLastClippingEnabled = YES;//避免文字显示不全 这个属性很重要
        
        xAxis.drawGridLinesEnabled = NO;//是否画网格
        xAxis.gridColor = UIColor.redColor;//x轴对应网格线的颜色
        xAxis.gridLineWidth = 1;//x轴对应网格线的大小
        xAxis.gridLineDashLengths = @[@4,@2];  //虚线各段长度
    //    xAxis.labelRotationAngle = -30.0;//设置文字旋转角度
       

        //自定义数据显示格式
    //     NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    //    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    //    [formatter setPositiveFormat:@"#0.0"];
    //    formatter.positivePrefix = @"#";
    //    xAxis.valueFormatter = [[ChartDefaultAxisValueFormatter alloc]initWithFormatter:formatter];
        xAxis.valueFormatter = self;
        
        //加载动画时长
        [_lineChartView animateWithYAxisDuration:0.2 easingOption:ChartEasingOptionEaseInBack];
    }
    return _lineChartView;
}

#pragma mark --------------------chartView delegate ------------------
#pragma mark  ChartAxisValueFormatter
//- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis
//{
//    if ([axis isEqual:self.lineChartView.leftAxis]||[axis isEqual:self.lineChartView.rightAxis]) {
//        NSNumber *n = [NSNumber numberWithDouble:value];
//        return [n decimalPlacesWithoutRoundDownWithDigit:1];
//    }
//  
//    
//    NSNumber *n = [NSNumber numberWithDouble:value];
//    return [n decimalPlacesWithoutRoundDownWithDigit:1];
//}

- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis
{
    //电压保留一位小数  ,温度保留两位小数
    if ([axis isEqual:self.lineChartView.leftAxis]) {
        NSNumber *number =  [NSNumber numberWithDouble:value];
        NSString *strValue = [number decimalPlacesWithoutRoundDownWithDigit:1];
        return  [NSDecimalNumber decimalStringWithDoubleString:strValue nullStr:@"--"];
    }
    
    //电压保留一位小数  ,温度保留两位小数
    if ([axis isEqual:self.lineChartView.rightAxis]) {
        NSNumber *number =  [NSNumber numberWithDouble:value];
        NSString *strValue = [number decimalPlacesWithoutRoundDownWithDigit:2];
        return  [NSDecimalNumber decimalStringWithDoubleString:strValue nullStr:@"--"];
    }
    
    NSInteger index = (NSInteger)value;
    return  [self.chartModel.xTitlesArray safeObjectAtIndex:index];
}
#pragma mark 图表中数值被选中
-(void)chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight{
    
    [self.maskView updateModel:self.chartModel index:(NSInteger)highlight.x colors:self.colorList];
    
    ChartMarkerView *makerView = (ChartMarkerView*)chartView.marker;
    CGFloat off_x = 0;
    if(chartView.width - highlight.xPx < self.maskView.width)
    {
        off_x = -self.maskView.width;
    }else if (highlight.xPx < self.maskView.width/2){
        off_x = 0;
    }else{
        off_x = -self.maskView.width/2;
    }
    
    makerView.offset = CGPointMake(off_x, -self.maskView.height/2);
    
//    NSLog(@"----->chartView.maskView frame:%@",NSStringFromCGRect(chartView.maskView.frame)) ;
//    NSLog(@"----->self.maskView frame:%@",NSStringFromCGRect(self.maskView.frame)) ;
//    NSLog(@"------>entry.x=%f",entry.x);
//    NSLog(@"------>entry.y=%f",entry.y);
//    NSLog(@"------>highlight.x=%f",highlight.x);
    NSLog(@"------>highlight.xPx=%f",highlight.xPx);
//    NSLog(@"------>highlight.drawX=%f",highlight.drawX);
//    NSLog(@"------>highlight.y=%f",highlight.y);
//    NSLog(@"------>highlight.yPx=%f",highlight.yPx);
//    NSLog(@"------>highlight.drawY=%f",highlight.drawY);
//    NSLog(@"------>highlight.xPx=%f",chartView.xAxis.);
    NSLog(@"------>label_width=%f",chartView.xAxis.labelWidth);
       
    
    
}

#pragma mark 图表中的空白区域被选中
-(void)chartValueNothingSelected:(ChartViewBase *)chartView{
    NSLog(@"空白区域被选中");
}

#pragma mark 图表被缩放
-(void)chartScaled:(ChartViewBase *)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY{
//    NSLog(@"图表被缩放");
    //根据缩放调整显示间隔
//    if(scaleX>=3){
//        self.lineChartView.xAxis.granularity = 1;
//    }else if(scaleX>=2){
//        self.lineChartView.xAxis.granularity = 2;
//    }
//    chartView.xAxis.granularity = self.chartModel.xTitlesArray.count/8*scaleX;
    NSLog(@"------>图表缩放倍数:%f",scaleX);
    
    NSString *time = @"23:23";
    CGFloat width = [time getStringWidthFont:self.lineChartView.xAxis.labelFont limitHeight:25];
//    NSLog(@"----->333%@",chartView.xAxis.yy_modelDescription);
    
}

#pragma mark 图表被移动
-(void)chartTranslated:(ChartViewBase *)chartView dX:(CGFloat)dX dY:(CGFloat)dY{
//    NSLog(@"图表被移动");
}


#pragma mark ------ lazy load
-(NSMutableArray *)unitArr
{
    if(!_unitArr)
    {
        _unitArr = [NSMutableArray array];
    }
    return _unitArr;;
}
-(NSMutableArray *)pointViewArr
{
    if(!_pointViewArr)
    {
        _pointViewArr = [NSMutableArray array];
    }
    return _pointViewArr;;
}

@end
